# -*- coding: utf-8 -*-

#
# peerscape.http.controllers.group
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors:
#       Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement

import cgi
from webob import Response
from webob.exc import HTTPMovedPermanently, HTTPTemporaryRedirect
from peerscape.http.controllers import BaseController
from peerscape.core.policy import Unauthorized

class Group(BaseController):
    def index(self, req):
        # check the type before proceeding
        redir_url = self.require_type(req, ['group'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('group.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()

            v['profile_fields'] = self.process_group_profile(db, v['hexlabel'])
            v['visibility'] = self.get_group_link_visibility(db, v['hexlabel'])
            v['member_list'] = self.process_member_list(db, v['hexlabel'], v['my_iid'])
            
            v['events_list'] = self.process_events_list(db, v['hexlabel'], v['my_iid'])
            v['atom_list'] = self.process_atom_list(db, v['hexlabel'])
            v['content_list'] = self.process_content_list(db, v['hexlabel'])
            v['invitations'] = self.get_invitations(db)
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            # make it so
            return view.render(**v)
        else:
            return None


    def edit_picture(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['member_list'] = self.process_member_list(db, v['hexlabel'], v['my_iid'])
            
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            if req.POST.has_key('action'):
                if req.POST['action'] == 'delete':
                    # delete picture
                    db.clear_profile_picture(v['hexlabel'])

            if req.POST.has_key('generic:0:picture'):
                # save new picture
                upload = req.POST['generic:0:picture']
                if upload.__class__ == cgi.FieldStorage:
                    with upload.file as f:
                        newpic = f.read()

                    db.set_profile_picture(v['hexlabel'], newpic)

            # redirect to profile
            redir_url = '/group/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('group.edit_picture.html')

            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)

                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['member_list'] = self.process_member_list(db, v['hexlabel'], v['my_iid'])
                
                v['is_member'] = v['my_iid'] in v['member_list']['index']
                v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

                v['profile_fields'] = self.process_group_profile(db, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None

    def edit(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['is_self']  = db.get_my_iid() == v['hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['member_list'] = self.process_member_list(db, v['hexlabel'], v['my_iid'])
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            # get the generic fields
            generic_fields = dict([(key,val) for key,val in req.POST.items() if key.startswith('generic')])

            # update name
            name = (generic_fields['generic:0:name'] or '').strip()
            if name:
                db.set_profile_name(v['hexlabel'], name)

            # update about
            db.set_profile_text(v['hexlabel'], generic_fields['generic:0:about'] or '', public=True)

            # redirect to profile
            redir_url = '/group/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('group.edit.html')

            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)

                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['is_self']  = db.get_my_iid() == v['hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['member_list'] = self.process_member_list(db, v['hexlabel'], v['my_iid'])
                v['is_member'] = v['my_iid'] in v['member_list']['index']
                v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

                v['profile_fields'] = self.process_group_profile(db, v['hexlabel'])
                if not v['profile_fields']['generic']['about']['values'][0]['value']:
                    v['profile_fields']['generic']['about']['values'][0]['value'] = ''

                # engage -->
                return view.render(**v)
            else:
                return None

